package cn.jbooter.ctx.autoconfigure.container;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 获取spring容器上下文
 * 
 * @author HeJian
 *
 */
public class ContextUtils implements ApplicationContextAware {

	/** spring 上下文 **/
	private static ApplicationContext context;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		context = applicationContext;
	}

	/**
	 * 获取ApplicationContext
	 * 
	 * @return
	 */
	public static ApplicationContext getContext() {
		return context;
	}

	/**
	 * 获取bean
	 * 
	 * @param t
	 * @return
	 */
	public static <T> T getBean(Class<T> t) {
		try {
			T bean = context.getBean(t);
			return bean;
		} catch (BeansException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 通过beanname获取bean
	 * 
	 * @param beanName
	 * @return
	 */
	public static Object getBean(String beanName) {
		try {
			Object bean = context.getBean(beanName);
			return bean;
		} catch (BeansException e) {
			e.printStackTrace();
			return null;
		}
	}

}
